package com.fh.utils;

import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.util.Base64;

@Component
public class PasswordUtil {
    private static final String Hash_ALGORITHM = "SHA-256";
    public  String encrypt(String input) {
        try {
            // 获取SHA-256消息摘要实例
            MessageDigest digest = MessageDigest.getInstance(Hash_ALGORITHM);

            // 使用消息摘要对输入字节数组进行哈希计算
            byte[] hashedBytes = digest.digest(input.getBytes());

            // 将字节数组编码为 Base64 字符串，以便在存储和传输时使用
            return Base64.getEncoder().encodeToString(hashedBytes);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public boolean verify(String oldPassword, String newPassword) {
        try {
            // 获取 SHA-256 消息摘要实例
            MessageDigest digest = MessageDigest.getInstance(Hash_ALGORITHM);

            // 对原始密码进行哈希计算
            byte[] hashBytes = digest.digest(oldPassword.getBytes());

            // 将哈希计算得到的字节数组转换成 Base64 编码后的字符串
            String hashedRawPassword = Base64.getEncoder().encodeToString(hashBytes);

            // 比较哈希值和原始密码的哈希值是否相同
            return hashedRawPassword.equals(newPassword);

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}